package com.ac.controller;

import com.ac.config.ResponseEntity;
import com.ac.entity.Device;
import com.ac.service.DeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/device")
public class DeviceController {

    @Autowired
    private DeviceService deviceService;

    private int pageRows = 2;

    @GetMapping("/query")
    public ResponseEntity query(Integer buildingId,Integer pageIndex){
        if(pageIndex == null){
            pageIndex = 1;
        }
        if(pageIndex < 1){
            pageIndex = 1;
        }
        //总行数
        int rowsCount = deviceService.queryDeviceCount(buildingId);
        //总页数
        int pageCount = 0;
        if(rowsCount % pageRows == 0){
            pageCount = rowsCount / pageRows;
        }else{
            pageCount = rowsCount / pageRows + 1;
        }
        HashMap<String,Object> pageInfo = new HashMap<>();
        //总页数
        pageInfo.put("pageCount",pageCount);

        //如果没有数据，则直接返回空内容
        if(pageCount == 0){
            pageInfo.put("pageIndex",0);
            pageInfo.put("list",new ArrayList<Device>());
            return ResponseEntity.success(pageInfo);
        }
        if(pageIndex > pageCount){
            pageIndex = pageCount;
        }
        //第几页
        pageInfo.put("pageIndex",pageIndex);
        //第几页转换成第几行开始
        int startIndex = (pageIndex-1) * pageRows;
        List<Device> deviceList = deviceService.queryDevice(buildingId,startIndex,pageRows);
        pageInfo.put("list",deviceList);
        return ResponseEntity.success(pageInfo);
    }

    @PostMapping("/update")
    public ResponseEntity updateStatus(@RequestBody Device device){
        deviceService.updateStatus(device);
        return ResponseEntity.success();
    }

    @PostMapping("/add")
    public ResponseEntity add(@RequestBody Device device){
        device.setStatus(0);
        deviceService.add(device);
        return ResponseEntity.success();
    }
}
